import React from "react";

class DemoA extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      num: 1,
    }
    this.add = this.add.bind(this)
  }
  add() {  // 1 1    2 1    3 2    4 3
    console.log("---- 1 ", this.state.num);
    // 每一次setState都会重新render，但是多次setState,会进行合并，为了提升性能。
    this.setState(_ => ({ num: _.num + 1 }), () => { console.log("---- 3 ", this.state.num); })
    this.setState(_ => ({ num: _.num + 1 }), () => { console.log("---- 4 ", this.state.num); })
    console.log("---- 2 ", this.state.num);
  }
  render() {
    console.log("render...");  // 两次
    let { num } = this.state;
    return (
      <div>
        <h1>类组件</h1>
        <h2>{num}</h2>
        <button onClick={this.add}>+1</button>
      </div>
    )
  }
}

export default DemoA

